<template>
  <div class="store-basics-edit-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{title}}</span>
      </div>
      <el-form ref="form" id="form" :model="form" :rules="rules" label-width="135px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="店铺名称" prop="supplierName">
              <el-input v-model="form.supplierName" placeholder="请输入店铺名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="店长姓名" prop="realName">
              <el-input v-model="form.realName" placeholder="请输入店长姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="手机号码" prop="userPhone">
              <el-input v-model="form.userPhone" type="number" autocomplete placeholder="请输入手机号码" @mousewheel.native.prevent />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="form.idCard" placeholder="请输入身份证号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="店铺状态">
              <el-select v-model="form.isCloseStore" placeholder="请选择店铺状态">
                <el-option v-for="dict in isCloseStoreOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="店铺开通状态">
              <el-select v-model="form.isOpen" placeholder="请选择店铺开通状态">
                <el-option v-for="dict in isOpenOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="扫码核销">
              <el-select v-model="form.isScan" placeholder="请选择是否开启扫码核销">
                <el-option v-for="dict in isActivedOptions" :key="dict.dictValue" :label="dict.dictLabel" :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <div class="info-div main-pic">
          <div class="div-title">店铺图标</div>
          <div class="pic-div">
            <el-upload :action="uploadActionMain" :headers="uploadHeaders" :multiple="false" :file-list="mainPic"
              list-type="picture-card" :on-success="handleUploadSuccMain">
              <i slot="default" class="el-icon-plus"></i>
              <div slot="file" slot-scope="{file}">
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                <span class="el-upload-list__item-actions">
                  <span class="el-upload-list__item-preview" @click="handlePicPreview(file)">
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span class="el-upload-list__item-delete" @click="handlePicRemove(file, mainPic)">
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div>
            </el-upload>
          </div>
        </div>
        <el-row :gutter="20">
          <el-form-item class="form-btn-bar">
            <el-button type="primary" @click="submitForm">保 存</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </el-card>

    <el-dialog :visible.sync="showPicPreview">
      <img width="100%" :src="picPreviewUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
  import Editor from '@/components/Editor';
  import {
    getPreId,
    getSuppliers,
    addSuppliers,
    updateSuppliers
  } from "@/api/suppliers/suppliers";
  import {
    addFile,
    delFiles,
    getFileList,
    editFile
  } from "@/api/basic/file"

  export default {
    name: "ProjectEdit",
    components: {
      Editor
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 标题
        title: "",
        // 商品分类表格数据
        SUPPLIERSList: [],
        uploadActionMain: "",
        uploadHeaders: {
          Authorization: 'Bearer ' + this.$store.state.user.token,
          lesseeId: this.$store.state.user.lesseeid || '13'
        },
        mainPic: [],
        showPicPreview: false,
        picPreviewUrl: "",
        // 是否显示弹出层
        open: false,
        // 店铺状态字典
        isCloseStoreOptions: [],
        // 店铺开通状态字典
        isOpenOptions: [],
        isActivedOptions:[],
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          supplierName: [{
            required: false,
            message: '请填写店铺名称',
            trigger: 'blur'
          }],
          realName: [{
            required: false,
            message: '请填写店长姓名',
            trigger: 'blur'
          }],
          idCard: [{
            required: false,
            message: '请填写身份证号',
            trigger: 'blur'
          }]
        }
      }
    },
    created() {
      const that = this;
      that.getDicts("is_active").then(response => {
        that.isCloseStoreOptions = response.data;
        that.isCloseStoreOptions.forEach(function(item){
          if (item.dictLabel == '是') {
            item.dictLabel = '营业'
          } else {
            item.dictLabel = '未营业'
          }
        })
      });
      that.getDicts("is_active").then(response => {
        that.isActivedOptions =  response.data;
      });
      that.getDicts("is_active").then(response => {
        that.isOpenOptions = response.data;
        console.log('开通状态:');
        console.log(that.isOpenOptions);
        that.isOpenOptions.forEach(function(item){
          if (item.dictLabel == '是') {
            item.dictLabel = '开通'
          } else {
            item.dictLabel = '未开通'
          }
        })
      });
      that.reset(function() {
        that.getDetailInfo(that.$route.params.id);
      })
    },
    methods: {
      handlePicPreview(file) {
        this.picPreviewUrl = file.url
        this.showPicPreview = true
      },

      handlePicRemove(file, fileList) {
        return this.$confirm('确定删除该图片?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let fileId = file.id || (file.response.fileId)
          if (fileId) {
            delFiles({
              ids: fileId
            }).then(response => {
              if (response.code !== 200) {
                this.msgError(response.msg)
              } else {
                let findIndex = fileList.findIndex(obj => {
                  return obj.uid == file.uid
                })
                if (findIndex >= 0) {
                  fileList.splice(findIndex, 1)
                }
              }
            })
          } else {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            let findIndex = fileList.findIndex(obj => {
              return obj.uid == file.uid
            })
            if (findIndex >= 0) {
              fileList.splice(findIndex, 1)
            }
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },

      editFile(file, sorting) {
        editFile({
          id: (file.id || file.response.fileId),
          sorting
        }, res => {})
      },
      handleUploadSuccMain(response, file, fileList) {
        if (this.mainPic.length) {
          let fileId = this.mainPic[0].id || this.mainPic[0].response.fileId
          delFiles({
            ids: fileId
          }).then(response => {})
        }
        console.log('上传的文件:');
        console.log(file);
        this.mainPic = [file]
        this.form.supplierIcon = response.url
      },
      setUploadAction(id) {
        this.uploadActionMain = process.env.VUE_APP_BASE_API + '/common/upload/SUPPLIERS?sourcessId=' + id +
          '&sourcessType=SUPPLIERS&isActive=是';
      },
      /** 提交按钮 */
      submitForm: function() {
        const that = this;
        that.$refs["form"].validate(valid => {
          if (valid) {
            if (!that.form.supplierName) {
              that.$message({
                type: 'warning',
                message: '请填写店铺名称'
              });
              return;
            }
            if (!that.form.realName) {
              that.$message({
                type: 'warning',
                message: '请填写店长姓名'
              });
              return;
            }
            let reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
            if (that.form.idCard) {
              if (!reg.test(that.form.idCard)) {
                that.$message({
                  type: 'warning',
                  message: '请输入正确的身份证号'
                });
                return;
              }
            } else {
              that.$message({
                type: 'warning',
                message: '请填写身份证号码'
              });
              return;
            }
            if (!that.form.isTb) {
              that.form.isTb = '1';
            }
            if (that.title == "修改商铺基本信息") {
              updateSuppliers(that.form).then(response => {
                if (response.code === 200) {
                  that.msgSuccess("修改成功");
                  that.open = false;
                  that.closeSelectedTag(that.$route);
                }
              });
            } else {
              addSuppliers(that.form).then(response => {
                if (response.code === 200) {
                  that.msgSuccess("新增成功");
                  that.open = false;
                  that.closeSelectedTag(that.$route);
                }
              });
            }
          }
        });
      },
      isActive(route) {
        return route.path === this.$route.path
      },
      closeSelectedTag(view) {
        this.$store.dispatch('tagsView/delView', view).then(({
          visitedViews
        }) => {
          if (this.isActive(view)) {
            this.toLastView(visitedViews, view)
          }
        })
      },
      toLastView(visitedViews, view) {
        const latestView = visitedViews.slice(-1)[0]
        if (latestView) {
          this.$router.push(latestView.fullPath)
        } else {
          if (view.name === 'Dashboard') {
            this.$router.replace({
              path: '/redirect' + view.fullPath
            })
          } else {
            this.$router.push('/')
          }
        }
      },
      getDetailInfo(id) {
        const that = this;
        if (id != "new") {
          getSuppliers(id).then(response => {
            that.form = response.data;
            that.setUploadAction(that.form.id);
            // 根据url创建文件对象：
            if (that.form.supplierIcon) {
              // 获取图片
              console.log('sourcessId：' + that.form.id);
              getFileList({
                sourcessId: that.form.id,
                sourcessType: 'SUPPLIERS'
              }).then(rs => {
                if (rs.code == 200) {
                  that.mainPic = rs.data || rs.rows || [];
                  if (that.mainPic.length > 0) {
                    that.mainPic.forEach(function(item) {
                      item.url = item.fileFullUrl;
                    })
                  }
                }
              })
            }
            that.title = "修改商铺基本信息"
          })
        } else {
          that.getPreIdFn();
          that.title = "添加商铺基本信息"
        }
      },
      getPreIdFn() {
        const that = this;
        // 文件上传: 新增记录提交前，获取预定的记录id, 提交时要提交此预定的记录id
        getPreId({}).then(response => {
          console.log('获取preId:');
          console.log(response);
          if (response.code === 200) {
            const data = response.data;
            if (data) {
              that.setUploadAction(data);
              that.form.id = data;
              console.log('preId:' + that.form.id);
            }
          }
        });
      },
      // 表单重置
      reset(call) {
        this.form = {
          id: undefined,
          createBy: undefined,
          createTime: undefined,
          updateBy: undefined,
          updateTime: undefined,
          isActive: "1", // 店铺状态
          lesseeId: "13",
          isCloseStore: '1', // 店铺状态
          isOpen: '1', // 店铺开通状态
          isTb: '1', // 店铺是否同步所有商品
          supplierName: undefined,
          supplierIcon: undefined,
          realName: undefined,
          userPhone: undefined,
          idCard: undefined
        };
        this.resetForm("form");
        if (call) {
          call()
        }
      }
    }
  }
</script>

<style>
  .editor-content .quill-editor.editor {
    height: 500px
  }

  .form-btn-bar {
    margin-top: 30px;
    text-align: center;
  }

  /*搜索框*/
  .search {
    width: 100%;
  }

  .input-group {
    position: relative;
    display: table;
    border-collapse: separate;
  }

  * {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
  }

  .btn {
    display: inline-block;
    padding: 6px 12px;
    margin-bottom: 0;
    font-size: 14px;
    font-weight: 400;
    line-height: 1.42857143;
    text-align: center;
    white-space: nowrap;
    vertical-align: middle;
    -ms-touch-action: manipulation;
    touch-action: manipulation;
    cursor: pointer;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    background-image: none;
    border: 1px solid transparent;
    border-radius: 4px;
  }

  .form-control {
    display: block;
    width: 100%;
    height: 34px;
    padding: 6px 12px;
    font-size: 14px;
    line-height: 1.42857143;
    color: #555;
    background-color: #fff;
    background-image: none;
    border: 1px solid #ccc;
    border-radius: 4px;
    -webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
    -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
    -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
    transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
  }

  .input-group .form-control:first-child,
  .input-group-addon:first-child,
  .input-group-btn:first-child>.btn,
  .input-group-btn:first-child>.btn-group>.btn,
  .input-group-btn:first-child>.dropdown-toggle,
  .input-group-btn:last-child>.btn-group:not(:last-child)>.btn,
  .input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle) {
    border-top-right-radius: 0;
    border-bottom-right-radius: 0;
  }

  .input-group .form-control,
  .input-group-addon,
  .input-group-btn {
    display: table-cell;
  }

  .input-group .form-control {
    position: relative;
    z-index: 2;
    float: left;
    width: 100%;
    margin-bottom: 0;
  }

  button,
  input,
  select,
  textarea {
    font-family: inherit;
    font-size: inherit;
    line-height: inherit;
  }

  button,
  input,
  optgroup,
  select,
  textarea {
    margin: 0;
    font: inherit;
    color: inherit;
  }

  .info-div {
    padding: 20px 20px 20px 65px;
  }

  .pic-div {
    border: 1px dotted #9e9e9e;
    border-radius: 10px;
    padding: 10px;
  }

  .div-title {
    margin-bottom: 20px;
    font-size: 14px;
    font-weight: 700;
    color: #606266;
  }

  .describe-pic .el-upload-list--picture-card .el-upload-list__item {
    display: block;
    width: 50%;
    height: auto;
    margin: 0;
    border: none;
    border-radius: 0;
  }

  .describe-pic .el-upload-list--picture-card .el-upload-list__item-thumbnail {
    vertical-align: top;
  }

  .describe-pic .el-upload--picture-card {
    margin-top: 20px;
    width: 50%;
    height: auto;
  }

  .el-dialog__body {
    padding: 10px 20px 30px 20px;
  }

  .attrs-btn-div {
    text-align: center;
    margin-top: 30px;
  }

  .goods-attrs-btn-bar {
    text-align: right;
    margin-bottom: 20px;
  }

  .input-group .form-control.getAddress {
    width: 85%;
  }

  .searchBtn {
    width: 15%;
    float: right;
    border-radius: 0 4px 4px 0;
    background: #dca131;
    color: #fff;
  }

  /*提示语*/
  .prompt {
    color: #e84720;
    font-size: 14px;
    font-family: '微软雅黑';
    margin: 5px 10px;
  }

  .validate {
    position: absolute;
    bottom: 10px;
    right: 20px;
    color: #e84720;
  }

  .test {
    display: inline-block;
    width: 20px;
    height: 10px;
    background: rgba(239, 194, 192, 0.38);
  }

  /*地图*/
  .map {
    padding: 10px 30px;
    border: 1px solid #ddd;
    border-radius: 10px;
    margin-bottom: 20px;
  }

  #containerMap {
    margin: 10px auto;
    width: 100%;
    min-height: 470px;
  }

  /*经纬度设置*/
  .latLng {
    text-align: center;
    margin: 20px auto;
  }

  .latlngSpan {
    font-size: 16px;
  }

  .latlngInput {
    width: 200px;
    height: 25px;
    outline: none;
    background: #fff;
  }
</style>
